package cn.gaozhong.ymcc.service.impl;

import cn.gaozhong.ymcc.constants.CourseConstants;
import cn.gaozhong.ymcc.doc.CourseDoc;
import cn.gaozhong.ymcc.domain.*;
import cn.gaozhong.ymcc.dto.CourseDto;
import cn.gaozhong.ymcc.feign.CourseSearchFeignClient;
import cn.gaozhong.ymcc.feign.MediaFileFeignClient;
import cn.gaozhong.ymcc.mapper.CourseMapper;
import cn.gaozhong.ymcc.result.JSONResult;
import cn.gaozhong.ymcc.service.*;
import cn.gaozhong.ymcc.util.AssertUtil;
import cn.gaozhong.ymcc.util.StrUtils;
import cn.gaozhong.ymcc.vo.CourseDetailVo;
import cn.gaozhong.ymcc.vo.CourseItemVo;
import cn.gaozhong.ymcc.vo.CourseOrderInfoVc;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author GZ.gaozhong
 * @since 2022-07-21
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements ICourseService {
    @Autowired
    private ITeacherService teacherService;
    @Autowired
    private ICourseDetailService courseDetailService;
    @Autowired
    private ICourseMarketService courseMarketService;
    @Autowired
    private ICourseResourceService courseResourceService;
    @Autowired
    private ICourseTeacherService courseTeacherService;
    @Autowired
    private ICourseSummaryService courseSummaryService;
    @Autowired
    private ICourseTypeService courseTypeService;
    @Autowired
    private CourseSearchFeignClient courseSearchFeignClient;
    @Autowired
    private MediaFileFeignClient mediaFileFeignClient;
    @Autowired
    private ICourseChapterService courseChapterService;
    @Override
    public void save(CourseDto dto) {
        Course course = dto.getCourse();
        CourseDetail courseDetail = dto.getCourseDetail();
        CourseMarket courseMarket = dto.getCourseMarket();
        CourseResource courseResource = dto.getCourseResource();
        List<Long> teacharIds = dto.getTeacharIds();
        //课程不能被注册
        Course courseTmp = selectByName(course.getName());
        AssertUtil.isNull(courseTmp, CourseConstants.COURSE_TYPE);
        //保存课程
        course.setStatus(Course.STATUS_OFFLINE);
        course.setLoginId(1L);
        course.setLoginUserName("yhptest1");
        List<Teacher> teachers = teacherService.selectBatchIds(teacharIds);
        //整成stream
        StringBuilder sb = new StringBuilder();
        teachers.forEach(teacher -> {
            sb.append(teacher.getName()).append(",");
        });
        course.setTeacherNames(sb.toString());
        insert(course);
        //保存课程详情
        courseDetail.setId(course.getId());
        courseDetailService.insert(courseDetail);
        //保存课程销售
        courseMarket.setId(course.getId());
        courseMarketService.insert(courseMarket);
        //保存课程讲师
        teacharIds.forEach(id->{
            CourseTeacher courseTeacher = new CourseTeacher();
            courseTeacher.setCourseId(course.getId());
            courseTeacher.setTeacherId(id);
            courseTeacherService.insert(courseTeacher);
        });
        //保存课程资源
        courseResource.setCourseId(course.getId());
        courseResourceService.insert(courseResource);
        //初始化课程统计
        CourseSummary courseSummary = new CourseSummary();
        courseSummary.setId(course.getId());
        courseSummaryService.insert(courseSummary);
        //课程类型表中的课程数
        CourseType type = courseTypeService.selectById(course.getCourseTypeId());
        type.setTotalCount(type.getTotalCount() + 1);
        courseTypeService.updateById(type);
    }

    private Course selectByName(String name) {
        Wrapper<Course> tWrapper = new EntityWrapper<Course>();
        tWrapper.eq("name",name);
        return selectOne(tWrapper);
    }

    @Override
    public void onLineCourse(Long courseId) {
        //根据课程ID查询课程，判断可是是否存在
        Course course = selectById(courseId);
        AssertUtil.isNotNull(course,"课程不能为空");
        //修改课程状态为上架，填写上架时间
        course.setStatus(Course.STATUS_ONLINE);
        course.setOnlineTime(new Date());
        updateById(course);
        CourseType type = courseTypeService.selectById(course.getCourseTypeId());
        CourseMarket courseMarket = courseMarketService.selectById(courseId);
        CourseSummary courseSummary = courseSummaryService.selectById(courseId);
        //保存课程相关内容到Es
        CourseDoc doc = new CourseDoc();
        BeanUtils.copyProperties(course,doc);
        doc.setCourseTypeName(type.getName());
        BeanUtils.copyProperties(courseMarket,doc);
        BeanUtils.copyProperties(courseSummary,doc);
        String chargeName = courseMarket.getCharge() == 1 ? "免费" : "收费";
        doc.setChargeName(chargeName);

        // 为service-search编写feign
        JSONResult jsonResult = courseSearchFeignClient.saveCourse(doc);
        AssertUtil.isTrue(jsonResult.isSuccess(),"课程发布失败");


    }

    @Override
    public CourseDetailVo detail(Long courseId) {
        AssertUtil.isNotNull(courseId,"请求非法");
        Course course = selectById(courseId);
        AssertUtil.isNotNull(course,"请求非法");
        boolean onLine = course.getStatus() == Course.STATUS_ONLINE;
        AssertUtil.isTrue(onLine,"请求非法");//课程没有上线

        CourseDetail courseDetail = courseDetailService.selectById(courseId);
        CourseMarket courseMarket = courseMarketService.selectById(courseId);
        CourseSummary courseSummary = courseSummaryService.selectById(courseId);
        Wrapper<CourseTeacher> ctwrapper = new EntityWrapper<>();
        ctwrapper.eq("course_id",courseId);
        List<CourseTeacher> courseTeachers = courseTeacherService.selectList(ctwrapper);
        List<Long> teacherIds = courseTeachers.stream().map(teacher -> teacher.getTeacherId()).collect(Collectors.toList());
        List<Teacher> teachers = teacherService.selectBatchIds(teacherIds);
        //查询章节
        Wrapper<CourseChapter> ccwrapper = new EntityWrapper<>();
        ccwrapper.eq("course_id",courseId);
        List<CourseChapter> chapters = courseChapterService.selectList(ccwrapper);
        //要为每一个章节查询对应的视屏
        //1.media微服务编写controller查询章节视屏
        //2.为media服务编写Feign接口+降级方案
        //3.course微服务依赖media的Feign接口，调用media查询章节视屏
        chapters.forEach(chapter->{
            JSONResult jsonResult = mediaFileFeignClient.searchMediaFiles(chapter.getId());//你可以搞成批量查询
            if(jsonResult.isSuccess() && jsonResult.getData() != null){
                List<MediaFile> fileList = JSONObject.parseArray(jsonResult.getData().toString(), MediaFile.class);
                chapter.getMediaFiles().addAll(fileList);
            }
        });
        CourseDetailVo vo = new CourseDetailVo();
        vo.setCourse(course);
        vo.setCourseChapters(chapters);
        vo.setCourseMarket(courseMarket);
        vo.setCourseSummary(courseSummary);
        vo.setCourseDetail(courseDetail);
        vo.setTeachers(teachers);
        return vo;
    }

    @Override
    public CourseItemVo orderInfo(String courseIds) {
        List<Long> ids = StrUtils.splitStr2LongArr(courseIds);
        Set<Long> setIds = ids.stream().collect(Collectors.toSet());
        boolean b = ids.size() == setIds.size();
        AssertUtil.isTrue(b,"请求非法");
        List<CourseOrderInfoVc> courseInfos = new ArrayList<>();
        BigDecimal totalAmount = new BigDecimal(0);
        for (Long id : setIds) {
            Course course = selectById(id);
            AssertUtil.isNotNull(course,"数据查询不到");
            CourseMarket courseMarket = courseMarketService.selectById(id);
            CourseOrderInfoVc courseOrderInfoVc = new CourseOrderInfoVc(course, courseMarket);
            courseInfos.add(courseOrderInfoVc);
            totalAmount = totalAmount.add(courseMarket.getPrice());
        }
        return new CourseItemVo(courseInfos,totalAmount);
    }
}
